﻿namespace GreenIsomer.Data.Entities.Ddl {

	public class ForeignKey {

		private ColumnRefCollection columns;

		public ForeignKey() {
			columns = new ColumnRefCollection();
			ReferencedTable = new TableRef();
		}

		public string Name { get; set; }

		public ColumnRefCollection Columns {
			get { return columns; }
		}

		public TableRef ReferencedTable { get; set; }

		public virtual void WriteCreateScript(DdlWriter writer, string tableName, string schema) {
			if(ReferencedTable == null) return;

			writer.StartNewLine();

			writer.WriteScript("ALTER TABLE");

			writer.AddSpace();
			writer.WriteSchemaPrefix(schema);
			writer.WriteName(tableName);
			writer.AddSpace();

			writer.WriteScript("ADD CONSTRAINT");

			writer.AddSpace();
			writer.WriteName(Name);
			writer.AddSpace();

			writer.WriteScript("FOREIGN KEY");

			writer.AddSpace();
			Columns.WriteScript(writer);
			writer.AddSpace();

			writer.WriteScript("REFERENCES");

			writer.AddSpace();
			writer.WriteSchemaPrefix(ReferencedTable.Schema);
			writer.WriteName(ReferencedTable.Name);
			writer.AddSpace();

			ReferencedTable.Columns.WriteScript(writer);

			writer.WriteScript(";");
		}

		public virtual void WriteDropScript(DdlWriter writer, string tableName, string schema) {

			writer.StartNewLine();

			writer.WriteScript("ALTER TABLE");

			writer.AddSpace();
			writer.WriteSchemaPrefix(schema);
			writer.WriteName(tableName);
			writer.AddSpace();

			writer.WriteScript("DROP CONSTRAINT");

			writer.AddSpace();
			writer.WriteName(Name);
			writer.WriteScript(";");
		}

	}

}